package mrusanov.nation

import mrusanov.player.{PlayerType, PlayerTypeInfo, PlayerTypeGenerator}
import mrusanov.view._
import mrusanov.terrain._
import xml.{Node, XML}
import java.io.File
import mrusanov.league.{LeagueInfo, LeagueInfoSystem}
import mrusanov.team.Club

object NationsLoader {
  lazy val nations:Vector[Nation] = loadNations

  private def loadNations:Vector[Nation] = {
    val path = getClass.getResource("/conf/nations.xml").toURI
    val xml = XML.loadFile(new File(path))

    Vector() ++ (xml \ "nation") map (parseNation)
  }

  private def parseNation(node:Node):Nation = {
    val nationName = (node \ "@nameKey").toString()
    val popularity = (node \ "@popularity").toString().toInt
    val playerTypes = parsePlayerTypes((node \ "playerTypes")(0))
    val clubs = parseClubsList((node \ "clubs")(0))
    val leagueSystemInfo = parseLeagueSystem((node \ "leagueSystem")(0))
    new Nation(nationName, clubs, popularity, playerTypes, leagueSystemInfo)
  }

  private def parseLeagueSystem(node:Node):LeagueInfoSystem = {
    val leagues = (node \ "level").map(lg => {
      val level = (lg \ "@level").toString().toInt
      val teams = (lg \ "@teams").toString().toInt
      val leaguesCount = (lg \ "@leagues").toString().toInt
      val promoted = (lg \ "@promoted").toString().toInt
      val rounds = (lg \ "@rounds").toString().toInt
      new LeagueInfo(level, teams, leaguesCount, promoted, rounds)
    })

    new LeagueInfoSystem(leagues)
  }

  private def parseClubsList(node:Node):List[Club] = {
    (node \ "club").map(club => {
      val name = (club \ "@nameKey").toString()
      new Club(name)
    }).toList
  }

  private def parsePlayerTypes(node:Node):List[PlayerType] = {
    (node \ "playerType").map(pt => {
      val name = (pt \ "@name").toString()
      PlayerTypeGenerator.playerTypes(name)
    }).toList
  }
}
